<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品管理系统</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <h1 class="text-3xl font-bold mb-6 text-center text-gray-800">产品管理系统</h1>

        <!-- 新增产品按钮 -->
        <div class="mb-6 text-right">
            <button
                id="add-product-btn"
                class="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-6 rounded-lg transition duration-200 flex items-center ml-auto"
            >
                <i class="fa fa-plus mr-2"></i>新增产品
            </button>
        </div>

        <!-- 搜索表单 -->
        <div class="bg-white p-6 rounded-lg shadow-md mb-8">
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-1">
                    <label for="search-input" class="block text-sm font-medium text-gray-700 mb-1">搜索产品</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                            <i class="fa fa-search text-gray-400"></i>
                        </span>
                        <input
                            type="text"
                            id="search-input"
                            placeholder="输入产品名称..."
                            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200"
                        >
                    </div>
                </div>

                <div class="w-full md:w-auto">
                    <label for="category-select" class="block text-sm font-medium text-gray-700 mb-1">产品分类</label>
                    <select
                        id="category-select"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200"
                    >
                        <option value="">所有分类</option>
                        {% for category in categories %}
                            <option value="{{ category }}">{{ category }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div class="self-end">
                    <button
                        id="search-button"
                        class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-6 rounded-lg transition duration-200 flex items-center"
                    >
                        <i class="fa fa-search mr-2"></i>搜索
                    </button>
                </div>
            </div>
        </div>

        <!-- 新增产品模态框 -->
        <div id="add-product-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-lg transform transition-all scale-95 opacity-0" id="modal-content">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <h2 class="text-xl font-bold text-gray-800">新增产品</h2>
                        <button id="close-modal" class="text-gray-500 hover:text-gray-700">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                </div>

                <div class="p-6">
                    <form id="add-product-form">
                        <div class="mb-4">
                            <label for="product-name" class="block text-sm font-medium text-gray-700 mb-1">产品名称 <span class="text-red-500">*</span></label>
                            <input
                                type="text"
                                id="product-name"
                                name="name"
                                required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition duration-200"
                                placeholder="请输入产品名称"
                            >
                        </div>

                        <div class="mb-4">
                            <label for="product-category" class="block text-sm font-medium text-gray-700 mb-1">产品分类 <span class="text-red-500">*</span></label>
                            <input
                                type="text"
                                id="product-category"
                                name="category"
                                required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition duration-200"
                                placeholder="请输入产品分类"
                            >
                        </div>

                        <div class="mb-4">
                            <label for="product-price" class="block text-sm font-medium text-gray-700 mb-1">产品价格 <span class="text-red-500">*</span></label>
                            <input
                                type="number"
                                id="product-price"
                                name="price"
                                step="0.01"
                                min="0"
                                required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition duration-200"
                                placeholder="请输入产品价格"
                            >
                        </div>

                        <div class="mb-6">
                            <label for="product-description" class="block text-sm font-medium text-gray-700 mb-1">产品描述 <span class="text-red-500">*</span></label>
                            <textarea
                                id="product-description"
                                name="description"
                                rows="3"
                                required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition duration-200"
                                placeholder="请输入产品描述"
                            ></textarea>
                        </div>

                        <div class="flex justify-end gap-3">
                            <button
                                type="button"
                                id="cancel-add"
                                class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition duration-200"
                            >
                                取消
                            </button>
                            <button
                                type="submit"
                                class="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-6 rounded-lg transition duration-200 flex items-center"
                            >
                                <i class="fa fa-save mr-2"></i>保存产品
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 消息提示框 -->
        <div id="message-toast" class="fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300 flex items-center z-50"></div>

        <!-- 加载指示器 -->
        <div id="loading-indicator" class="hidden text-center py-8">
            <i class="fa fa-spinner fa-spin text-3xl text-blue-500"></i>
            <p class="mt-2 text-gray-600">正在加载...</p>
        </div>

        <!-- 结果区域 -->
        <div id="results-container" class="bg-white rounded-lg shadow-md overflow-hidden">
            <div id="results-header" class="px-6 py-4 border-b border-gray-200 bg-gray-50 hidden">
                <h2 class="text-xl font-semibold text-gray-800">产品列表</h2>
            </div>

            <div id="no-results" class="px-6 py-12 text-center hidden">
                <i class="fa fa-search-minus text-4xl text-gray-300 mb-4"></i>
                <p class="text-gray-500">没有找到匹配的产品</p>
            </div>

            <div id="results-list" class="divide-y divide-gray-200">
                <!-- 结果将通过JavaScript动态插入 -->
            </div>
        </div>
    </div>

    <script>
        // 等待DOM加载完成
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search-input');
            const categorySelect = document.getElementById('category-select');
            const searchButton = document.getElementById('search-button');
            const resultsList = document.getElementById('results-list');
            const resultsHeader = document.getElementById('results-header');
            const noResults = document.getElementById('no-results');
            const loadingIndicator = document.getElementById('loading-indicator');
            const addProductBtn = document.getElementById('add-product-btn');
            const addProductModal = document.getElementById('add-product-modal');
            const modalContent = document.getElementById('modal-content');
            const closeModal = document.getElementById('close-modal');
            const cancelAdd = document.getElementById('cancel-add');
            const addProductForm = document.getElementById('add-product-form');
            const messageToast = document.getElementById('message-toast');

            // 显示消息提示
            function showMessage(message, isError = false) {
                messageToast.textContent = message;
                messageToast.className = 'fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-x-0 transition-transform duration-300 flex items-center z-50';

                if (isError) {
                    messageToast.classList.add('bg-red-100', 'text-red-700', 'border', 'border-red-200');
                } else {
                    messageToast.classList.add('bg-green-100', 'text-green-700', 'border', 'border-green-200');
                }

                // 3秒后隐藏消息
                setTimeout(() => {
                    messageToast.classList.remove('translate-x-0');
                    messageToast.classList.add('translate-x-full');
                }, 3000);
            }

            // 显示模态框
            function showModal() {
                addProductModal.classList.remove('hidden');
                // 触发重排后添加动画类
                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100', 'transition-all', 'duration-300');
                }, 10);
                // 清空表单
                addProductForm.reset();
            }

            // 隐藏模态框
            function hideModal() {
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');

                setTimeout(() => {
                    addProductModal.classList.add('hidden');
                }, 300);
            }

            // 搜索功能
            function performSearch() {
                const query = searchInput.value.trim();
                const category = categorySelect.value;

                // 显示加载指示器
                loadingIndicator.style.display = 'block';
                resultsList.innerHTML = '';
                resultsHeader.classList.add('hidden');
                noResults.classList.add('hidden');

                // 构建查询URL
                const url = new URL("{% url 'search_products' %}", window.location.origin);
                if (query) url.searchParams.append('query', query);
                if (category) url.searchParams.append('category', category);

                // 发送Ajax请求
                fetch(url)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应不正常');
                        }
                        return response.json();
                    })
                    .then(data => {
                        // 隐藏加载指示器
                        loadingIndicator.style.display = 'none';

                        if (data.products.length > 0) {
                            resultsHeader.classList.remove('hidden');
                            noResults.classList.add('hidden');

                            // 清空并填充结果列表
                            resultsList.innerHTML = '';
                            data.products.forEach(product => {
                                const productElement = document.createElement('div');
                                productElement.className = 'px-6 py-4 hover:bg-gray-50 transition duration-150';
                                productElement.innerHTML = `
                                    <div class="flex flex-col md:flex-row md:items-center justify-between">
                                        <div>
                                            <h3 class="text-lg font-semibold text-gray-800">${product.name}</h3>
                                            <p class="text-sm text-gray-500 mt-1">${product.category}</p>
                                            <p class="text-gray-700 mt-2">${product.description}</p>
                                        </div>
                                        <div class="mt-3 md:mt-0 font-bold text-blue-600">
                                            ¥${product.price}
                                        </div>
                                    </div>
                                `;
                                resultsList.appendChild(productElement);
                            });
                        } else {
                            // 没有找到结果
                            resultsHeader.classList.add('hidden');
                            noResults.classList.remove('hidden');
                        }
                    })
                    .catch(error => {
                        console.error('查询出错:', error);
                        loadingIndicator.style.display = 'none';
                        resultsHeader.classList.add('hidden');
                        noResults.classList.remove('hidden');
                        noResults.innerHTML = `
                            <i class="fa fa-exclamation-triangle text-4xl text-yellow-500 mb-4"></i>
                            <p class="text-gray-500">查询过程中出现错误，请重试</p>
                        `;
                    });
            }

            // 添加产品
            function addProduct(event) {
                event.preventDefault();

                // 获取表单数据
                const formData = {
                    name: document.getElementById('product-name').value.trim(),
                    category: document.getElementById('product-category').value.trim(),
                    price: document.getElementById('product-price').value.trim(),
                    description: document.getElementById('product-description').value.trim()
                };

                // 前端验证
                if (!formData.name) {
                    showMessage('请输入产品名称', true);
                    return;
                }

                if (!formData.category) {
                    showMessage('请输入产品分类', true);
                    return;
                }

                if (!formData.price || isNaN(formData.price) || parseFloat(formData.price) < 0) {
                    showMessage('请输入有效的产品价格', true);
                    return;
                }

                if (!formData.description) {
                    showMessage('请输入产品描述', true);
                    return;
                }

                // 发送Ajax请求
                fetch("{% url 'add_product' %}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken') // 获取CSRF令牌
                    },
                    body: JSON.stringify(formData)
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(data => {
                            throw new Error(data.message || '添加产品失败');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showMessage('产品添加成功');
                        hideModal();
                        // 重新加载产品列表
                        performSearch();
                    } else {
                        showMessage(data.message || '添加产品失败', true);
                    }
                })
                .catch(error => {
                    console.error('添加产品出错:', error);
                    showMessage(error.message || '添加产品时发生错误', true);
                });
            }

            // 获取CSRF令牌
            function getCookie(name) {
                let cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    const cookies = document.cookie.split(';');
                    for (let i = 0; i < cookies.length; i++) {
                        const cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) === (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }

            // 绑定事件
            searchButton.addEventListener('click', performSearch);
            addProductBtn.addEventListener('click', showModal);
            closeModal.addEventListener('click', hideModal);
            cancelAdd.addEventListener('click', hideModal);
            addProductForm.addEventListener('submit', addProduct);

            // 点击模态框外部关闭
            addProductModal.addEventListener('click', function(e) {
                if (e.target === addProductModal) {
                    hideModal();
                }
            });

            // 按Enter键执行搜索
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSearch();
                }
            });

            // 分类改变时执行搜索
            categorySelect.addEventListener('change', performSearch);

            // 初始加载所有产品
            performSearch();
        });
    </script>
</body>
</html>